package com.yuyou.fn.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.github.wens.mybatisplus.plugins.Page;
import com.yuyou.fn.common.util.BeanUtils;
import com.yuyou.fn.educational.entity.*;
import com.yuyou.fn.educational.service.*;
import com.yuyou.fn.educational.vo.*;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.beanutils.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.yuyou.fn.platform.entity.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.yuyou.fn.common.util.*;
/**
 * Created by Terry on 2017/3/7.
 *
 * @author Terry
 *         AdminEnrollApiController 报名
 */
@Controller
@RequestMapping("/api/admin")
public class AdminEnrollApiController extends AdminApiBaseController {


    @Resource
    private IStudentRegService studentRegService;

    @Resource
    private IStudentService studentService;

    @Resource
    private IStudentRefundService studentRefundService;

    @Resource
    private ICourseClassService courseClassService;

    @Resource
    private ICourseOrderService courseOrderService;

    /**
     * 查询学生是否存在
     *
     * @param
     * @return
     */
    @ApiOperation("通过电话号码/名字/手机查询学生是否存在")
    @RequestMapping(value = "/searchStudent", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Page<Student>> searchStudent(@RequestParam("keyword") String keyword , @RequestParam(value = "pageNo", defaultValue = "1") int pageNo, @RequestParam(value = "pageSize", defaultValue = "20") int pageSize, HttpServletRequest request) {
        Page<Student> studentList = studentService.findStudentByKeyword(keyword, pageNo, pageSize);
        return ReturnResult.success(studentList);
    }

    /**
     * 增加学生信息
     *
     * @param studentSaveOrUpdateVo
     * @return
     */
    @ApiOperation("增加或者修改学生信息")
    @RequestMapping(value = "/saveOrUpdateStudent", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> saveOrUpdateStudent(StudentSaveOrUpdateVo studentSaveOrUpdateVo, @RequestParam("guardianJsonStr") String guardianJsonStr) {
        List<StudentGuardianSaveOrUpdateVo> guardianList = JSON.parseObject(guardianJsonStr, new TypeReference<List<StudentGuardianSaveOrUpdateVo>>() {
        });
        studentSaveOrUpdateVo.setGuardianList(guardianList);
        Long studentId = studentService.saveOrUpdateStudent(studentSaveOrUpdateVo);
        return ReturnResult.success(studentId);
    }

    @ApiOperation("获取学生详细信息")
    @RequestMapping(value = "/studentDetail", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<StudentDetailVo> getStudentDetail(@RequestParam("studentId") Long studentId) {
        StudentDetailVo studentDetail = studentService.findStudentDetailByStudentId(studentId);
        return ReturnResult.success(studentDetail);
    }

    /**
     * 订单
     *
     * @param studentId
     * @param pageNo
     * @param pageSize
     * @return
     */
    @ApiOperation("学生订单列表")
    @RequestMapping(value = "/courseOrderList", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Page<CourseOrder>> courseOrderList(@RequestParam(value = "studentId") Long studentId, @RequestParam(value = "pageNo", defaultValue = "1") int pageNo, @RequestParam(value = "pageSize", defaultValue = "20") int pageSize, HttpServletRequest request) {
        Page<CourseOrder> page = courseOrderService.findCourseOrderList(studentId, pageNo, pageSize);
        return ReturnResult.success(page);
    }


    @ApiOperation("创建报名订单")
    @RequestMapping(value = "/createOfflineOrder", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<CourseOrder> createOfflineOrder(@RequestParam("studentRegInfoJsonStr") String studentRegInfoJsonStr , HttpServletRequest request) {

        StudentRegInfoVo studentRegInfoVo = JSONObject.parseObject(studentRegInfoJsonStr, StudentRegInfoVo.class);
        SysUser user = getUser(request);
        studentRegInfoVo.setOperator(user.getRealName());
        studentRegInfoVo.setFrom(0);//线下
        CourseOrder courseOrder = courseOrderService.createOrder(studentRegInfoVo);
        return ReturnResult.success(courseOrder);
    }

    /**
     * 在读班级信息
     *
     * @param studentId
     * @return
     */
    @ApiOperation("在读班级信息")
    @RequestMapping(value = "/studentReadClassList", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    private ReturnResult<List<StudentRegDetailVo>> studentReadClassList(@RequestParam(value = "studentId") Long studentId){

        StudentRegQueryVo studentRegQueryVo = new StudentRegQueryVo();
        studentRegQueryVo.setStudentId(studentId);
        studentRegQueryVo.setRegStatus(0);
        List<StudentReg> studentRegList = studentRegService.findStudentRegQuery(studentRegQueryVo);
        List<StudentRegDetailVo> regDetailVoList = toStudentRegDetailVo(studentRegList);
        return ReturnResult.success(regDetailVoList);
    }

    private List<StudentRegDetailVo> toStudentRegDetailVo(List<StudentReg> studentRegList) {
        //取出所有的classId,批量去查
        List<Long> classIds = BeanUtils.toList(studentRegList,"classId");
        List<CourseClass> classList = null;
        List<StudentRegDetailVo> regDetailVoList = null;
        if (classIds.size()>0) {
            classList = courseClassService.findByIds(classIds);

            Map<Long, CourseClass> courseClassMap = BeanUtils.toMap(classList, "classId");
            //尽量减少查库次数
            regDetailVoList = new ArrayList<>(studentRegList.size());

            for (StudentReg studentReg : studentRegList) {
                StudentRegDetailVo studentRegDetailVo = new StudentRegDetailVo();
                if (courseClassMap.get(studentReg.getClassId())!=null) {
                    studentRegDetailVo.setCourseClass(courseClassMap.get(studentReg.getClassId()));
                    studentRegDetailVo.setStudentReg(studentReg);
                    regDetailVoList.add(studentRegDetailVo);
                }
            }
        }
        return regDetailVoList;
    }

    @ApiOperation("缴费页面详情")
    @RequestMapping(value = "/courseOrderDetail", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    private ReturnResult<CourseOrderDetailVo> courseOrderDetail(@RequestParam(value = "courseOrderId") Long courseOrderId){

        CourseOrder courseOrder = courseOrderService.findById(courseOrderId);
        List<StudentReg> studentRegList = studentRegService.findStudentRegByCourseOrderId(courseOrderId);
        List<Long> classIds = BeanUtils.toList(studentRegList,"classId");
        List<CourseClass> courseClassList = courseClassService.findByIds(classIds);
        Map<Long, CourseClass> courseClassMap = BeanUtils.toMap(courseClassList,"classId");

        List<StudentRegDetailVo> regDetailVoList = new ArrayList<>(studentRegList.size());

        for (StudentReg studentReg : studentRegList){
            StudentRegDetailVo studentRegDetailVo = new StudentRegDetailVo();
            studentRegDetailVo.setStudentReg(studentReg);
            studentRegDetailVo.setCourseClass(courseClassMap.get(studentReg.getClassId()));
            regDetailVoList.add(studentRegDetailVo);
        }

        CourseOrderDetailVo vo = new CourseOrderDetailVo();
        vo.setCourseOrder(courseOrder);
        vo.setRegDetailVos(regDetailVoList);

        return ReturnResult.success(vo);
    }

    @ApiOperation("缴费")
    @RequestMapping(value = "/payCourseOrder")
    @ResponseBody
    public ReturnResult<Void> payCourseOrder(@RequestParam("courseOrderId") Long courseOrderId , @RequestParam("payAmount") BigDecimal payAmount , @RequestParam("payWay") Integer payWay , HttpServletRequest request  ){
        if( 4 == payWay ){
            return ReturnResult.fail("Not Permit");
        }
        courseOrderService.payCourseOrder( courseOrderId ,  payAmount ,  payWay , getUser(request).getRealName());
        return ReturnResult.success("ok");
    }

    @ApiOperation("转班第一步")
    @RequestMapping(value = "/showOldClass")
    @ResponseBody
    public ReturnResult<TurnClassVo> showOldClass(@RequestParam(value = "regId") Long regId){
        TurnClassVo studentReg = studentRegService.courseClassDetail(regId);
        return ReturnResult.success(studentReg);
    }

    @ApiOperation("转班新班级")
    @RequestMapping(value = "/showNewClass")
    @ResponseBody
    public ReturnResult<CourseClass> showNewClass(@RequestParam(value = "classId") Long classId){
        CourseClass courseClass = courseClassService.findById(classId);
        return ReturnResult.success(courseClass);
    }

    @ApiOperation("确定转班")
    @RequestMapping(value = "/turnClass")
    @ResponseBody
    public ReturnResult<Void> turnClass(ChooseClassVo chooseClassVo){
        studentRegService.changeClass(chooseClassVo);
        return ReturnResult.success("ok");
    }


    @ApiOperation("退款申请列表")
    @RequestMapping("/showStudentRefundList")
    @ResponseBody
    public ReturnResult<Page<StudentRefund>> showStudentRefundList(StudentRefundQueryVo studentRefundQueryVo, @RequestParam(value = "pageNo", defaultValue = "1") int pageNo, @RequestParam(value = "pageSize", defaultValue = "20") int pageSize, HttpServletRequest request) {
        SysUser sysUser = getUser(request);
        studentRefundQueryVo.setAreaTeamId(sysUser.getAreaTeamId());
        studentRefundQueryVo.setBusTeamId(sysUser.getBusTeamId());
        Page<StudentRefund> page = studentRefundService.findStudentRefundList(studentRefundQueryVo, pageNo, pageSize);
        return ReturnResult.success(page);
    }

    @ApiOperation("退款申请详情")
    @RequestMapping(value = "/studentRefundDetail", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<StudentRefund> studentRefundDetail(@RequestParam("studentRefundId") Long studentRefundId) {
        StudentRefund studentRefund = studentRefundService.findById(studentRefundId);
        return ReturnResult.success(studentRefund);
    }

    @ApiOperation("是否允许申请退款")
    @RequestMapping(value = "/allowStudentRefund", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<String> allowStudentRefund(@RequestParam("regId") Long regId) {
        StudentReg studentReg = studentRegService.findById(regId);
        if (studentReg.getChargingStatus() == 2) {
            return ReturnResult.success("ok");
        }
        return ReturnResult.success("fail");
    }

    @ApiOperation("创建退款申请")
    @RequestMapping("/saveStudentRefundClass")
    @ResponseBody
    public ReturnResult<Void> saveStudentRefundClass(StudentRefundSaveOrUpdateVo studentRefundSaveOrUpdateVo, HttpServletRequest request) {

        if (studentRefundSaveOrUpdateVo.getStudentRefundId() == null) {
            SysUser sysUser = getUser(request);
            studentRefundSaveOrUpdateVo.setCreateUserName(sysUser.getRealName());
            studentRefundSaveOrUpdateVo.setCreateUserId(sysUser.getUserId());
        }
        studentRefundService.saveOrUpdateStudentRefund(studentRefundSaveOrUpdateVo);
        return ReturnResult.success("ok");
    }

    @ApiOperation("修改退款申请")
    @RequestMapping("/changeStudentRefundStatus")
    @ResponseBody
    public ReturnResult<Void> changeStudentRefundStatus(@RequestParam("studentRefundId") Long studentRefundId , @RequestParam("status") Integer status ,@RequestParam("returnResult") String returnResult ) {
        studentRefundService.changeStatus(studentRefundId,status,returnResult);
        return ReturnResult.success("OK");
    }

    @ApiOperation("删除退款申请记录")
    @RequestMapping(value = "/delStudentRefund", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> delStudentRefund(@RequestParam(value = "studentRefundId") Long studentRefundId) {
        studentRefundService.deleteStudentRefund(studentRefundId);
        return ReturnResult.success("Ok");
    }

    @ApiOperation("班级历史")
    @RequestMapping(value = "/classHistoryList", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<List<ClassHistoryListVo>> classHistoryList(@RequestParam(value = "regStatus" , required = false ) Integer regStatus, @RequestParam(value="studentId") Long studentId)  {
        StudentRegQueryVo studentRegQueryVo = new StudentRegQueryVo();
        studentRegQueryVo.setStudentId(studentId);
        if(regStatus != null ){
            studentRegQueryVo.setRegStatus(regStatus);
        }
        List<StudentReg> studentRegList = studentRegService.findStudentRegQuery(studentRegQueryVo);
        List<StudentRegDetailVo> regDetailVoList = toStudentRegDetailVo(studentRegList);
        return ReturnResult.success(regDetailVoList);
    }

    @ApiOperation("获取班级退费信息")
    @RequestMapping(value = "/showClassMessage", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<RefundApplyVo> showClassMessage(@RequestParam(value = "regId") Long regId)  {
        RefundApplyVo refundApplyVo = studentRegService.refundApplyMessage(regId);
        return  ReturnResult.success(refundApplyVo);
    }

    @ApiOperation("报名列表")
    @RequestMapping(value = "/studentRegList", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> studentRegList(StudentRegQueryVo studentRegQueryVo , @RequestParam(value = "pageNo", defaultValue = "1") int pageNo, @RequestParam(value = "pageSize", defaultValue = "20") int pageSize) {
        Page<StudentReg> page = studentRegService.findStudentRegByQuery( studentRegQueryVo, pageNo, pageSize);
        return ReturnResult.success(page);
    }

}
